package cn.fl.ass.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.*;
import cn.fl.ass.service.IAssDealCarService;
import cn.fl.ass.vo.AssDealCarVO;
import cn.fl.ass.vo.AssProFileVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.system.api.ISysSequenceApiService;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.ass.facade.condition.AssDealCarQueryCondition;
import fl.ass.facade.condition.AssProFileQC;
import fl.ass.facade.condition.AssTransferInfoQC;
import fl.ass.facade.constant.AssFileConstant;
import fl.ass.facade.constant.DealCarFlowEnum;
import fl.ass.facade.constant.InterfaceConstants;
import fl.ass.facade.dto.AssDealCarTransferDTO;
import fl.ass.facade.dto.AssTransferInfoDTO;
import fl.flow.facade.flow.api.IFlowQueryApiService;
import fl.flow.facade.flow.condition.SysFlowSHQueryCondition;
import fl.flow.facade.flow.dto.SysFlowSHDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 转优车管理 控制层
 */
@Controller
@RequestMapping("/ass/dealcar/manage")
public class AssDealCarController extends BaseController {

    @Autowired
    private IAssDealCarService assDealCarService;

    @Autowired
    private ISysDictionaryApiService dictionaryApiService;

    @Autowired
    private IFlowQueryApiService flowQueryApiService;

    @Autowired
    private ISysSequenceApiService sysSequenceApiService;

    /**
     * 文件上传的服务
     */
    @Autowired
    private ISysUlFilesRecService sysUlFilesRecService;

    /**
     * 到转优车管理列表页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("ass/assDealCar/assDealCarManage");
        //是否需退款
        List<KeyValueVO> yesOrNo = this.dictionaryApiService.getKvList(DictionaryConstant.CODE_SYS_YES_NO_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
        //流程节点名称
        List<KeyValueVO> allList = DealCarFlowEnum.getAllList();

        view.addObject("isAssign", JSON.toJSONString(yesOrNo));
        view.addObject("taskDefKeyDic", JSON.toJSONString(allList));
        return view;
    }

    /**
     * 流程中的过户信息页签
     * @param request
     * @return
     */
    @RequestMapping(value = "/toTransInfoInFlow.do", method = {RequestMethod.GET})
    public ModelAndView toTransInfoInFlow(HttpServletRequest request) {
        // 转优车id
        String dealId = request.getParameter("dealId");
        // 节点标识
        String flag = request.getParameter("flag");
        ModelAndView view = new ModelAndView("ass/assDealCar/assDealCarTransInfoInFlow");
        view.addObject("dealId", dealId);
        view.addObject("flag", flag);
        return view;
    }

    /**
     * 到新增过户信息页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toAddAssTransInfo.do", method = {RequestMethod.GET})
    public ModelAndView toAddAssTransInfo(HttpServletRequest request) {
        // 转优车id
        String dealId = request.getParameter("dealId");
        ModelAndView view = new ModelAndView("ass/assDealCar/addAssTransferInfo");
        // 先获取过户信息id
        Long id = this.sysSequenceApiService.getFun("FN_GEN_ASS_TRANSFER_INFO_ID");
        // 过户项目
        List<KeyValueVO> category = this.dictionaryApiService.getKvList(InterfaceConstants.ASS_CATEGORY_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
        view.addObject("category", category);
        view.addObject("dealId", dealId);
        view.addObject("id", id);
        return view;
    }

    /**
     * 加载转优车管理列表数据
     * @param request
     * @return
     */
    @RequestMapping(value = "/loadListData.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, AssDealCarQueryCondition condition) {
        try {
            String currentPage = request.getParameter("page");
            String pageSize = request.getParameter("pagesize");

            Pager page = new Pager();
            page.setCurrentPage(StringUtils.isNotEmpty(currentPage) ? Integer.parseInt(currentPage) : 1);
            page.setEveryPage(StringUtils.isNotEmpty(pageSize) ? Integer.parseInt(pageSize) : 10);
            // 查询流程状态为2-流程中
            condition.setFlowStatusCd(InterfaceConstants.FLOW_STATUS_CD_2);
            page.setCondition(condition);

            page = assDealCarService.searchZycListPage(page);

            List<AssDealCarTransferDTO> resultList = (List<AssDealCarTransferDTO>) page.getResultList();
            /*if (CollectionUtils.isNotEmpty(resultList)) {
                Long currentMillisecond = new Date().getTime();
                Long expireMs = null;
                Long threeDay = (60 * 60 * 24 * 1000) * 3l;
                Long sevenDay = (60 * 60 * 24 * 1000) * 7l;
                for (AssDealCarTransferDTO dto : resultList) {
                    if (dto.getExpireTime() != null && (expireMs = dto.getExpireTime().getTime()) >= currentMillisecond) {
                        Long diffMs = expireMs - currentMillisecond;
                        if (diffMs < threeDay) {

                        } else if (diffMs < sevenDay) {

                        }
                    }
                }
            }*/

            ListPageVO<AssDealCarTransferDTO> listPage = new ListPageVO<>(resultList, page.getTotalCount());
            return listPage;
        } catch (BaseException e) {
            BaseLogUtils.newLogger("查询转优车管理列表数据业务异常！操作人：" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("查询转优车管理列表数据系统异常！操作人：" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
    }

    /**
     * 初始化过户信息资料grid
     * @param request
     * @return
     */
    @RequestMapping(value = "/initAssTransferInfoFileCfgGrid.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initAssTransferInfoFileCfgGrid(HttpServletRequest request) {
        try {
            String id = request.getParameter("id");
            if (StringUtils.isEmpty(id)) {
                throw new BaseException("过户信息id不能为空");
            }
            AssProFileQC condition = new AssProFileQC();
            condition.setAssTransferInfoId(Long.valueOf(id));
            condition.setOrgCd(AssFileConstant.ASS_PRO_ORG_CD);
            condition.setSysCd(AssFileConstant.ASS_PRO_SYS_CD);
            List<String> cfgCdList = new ArrayList<>();
            cfgCdList.add(AssFileConstant.ASS_PRO_FILE_CFG_CD_005);
            condition.setCfgCdList(cfgCdList);
            List<AssProFileVO> list = this.assDealCarService.searchAssTransferInfoFileCfgDtlAndFileCfg(condition);
            if (CollectionUtils.isNotEmpty(list)) {
                return new ListPageVO<AssProFileVO>(list, list.size());
            } else {
                return new ListPageVO<AssProFileVO>();
            }
        } catch (BaseException e) {
            BaseLogUtils.newLogger("初始化过户信息资料grid业务异常！操作人：" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("初始化过户信息资料grid业务异常！操作人：" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
    }

    /**
     * 在文件接收SYS_UL_FILE_REC表中增加文件上传记录
     *
     * @param request
     */
    @RequestMapping(value = "/uploadAssTransferInfoFile.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object uploadAssTransferInfoFile(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
        String fileParams = request.getParameter("fileParams");
        String cfgCd = request.getParameter("cfgCd");
        String cfgDtlCd = request.getParameter("cfgDtlCd");
        String orgCd = request.getParameter("orgCd");
        String id = request.getParameter("id");
        try {
            if (StringUtils.isBlank(id)) {
                BaseLogUtils.newLogger("上传项目资料文件失败,主键ID为空").setKeys("cfgCd:" + cfgCd, "cfgDtlCd:" + cfgDtlCd, "orgCd:" + orgCd).info();
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_FAIL);
            } else {
                boolean flag = this.sysUlFilesRecService.addAttchmnt(id, fileParams, cfgCd, cfgDtlCd, "ASS_TRANSFER_INFO", null, null, null, false, orgCd);
                if (!flag) {
                    BaseLogUtils.newLogger("上传诉讼记录资料文件失败").setKeys("id:" + id, "cfgCd:" + cfgCd, "cfgDtlCd:" + cfgDtlCd, "fileParams:" + fileParams).info();
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_FAIL);
                    return result;
                }
                BaseLogUtils.newLogger("上传诉讼记录资料文件成功").info();
            }
        } catch (BaseException e) {
            BaseLogUtils.newLogger("上传诉讼记录资料文件失败").setKeys("id:" + id, "cfgCd:" + cfgCd, "cfgDtlCd:" + cfgDtlCd, "fileParams:" + fileParams).setThrowable(e).setWarning(false).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("上传诉讼记录资料文件失败").setKeys("id:" + id, "cfgCd:" + cfgCd, "cfgDtlCd:" + cfgDtlCd, "fileParams:" + fileParams).setThrowable(e).setWarning(false).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
        return result;
    }

    /**
     * 加载过户信息列表数据
     * @param request
     * @return
     */
    @RequestMapping(value = "/initTransInfoList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initTransInfoList(HttpServletRequest request, AssTransferInfoQC condition) {
        try {
            String currentPage = request.getParameter("page");
            String pageSize = request.getParameter("pagesize");
            // 转优车id
            String dealId = request.getParameter("dealId");
            if (StringUtils.isEmpty(dealId)) {
                throw new BaseException("转优车id不能为空");
            }
            Pager page = new Pager();
            page.setCurrentPage(StringUtils.isNotEmpty(currentPage) ? Integer.parseInt(currentPage) : 1);
            page.setEveryPage(StringUtils.isNotEmpty(pageSize) ? Integer.parseInt(pageSize) : 10);
            condition.setDealId(Long.valueOf(dealId));
            page.setCondition(condition);
            page = assDealCarService.searchAssTransferInfoList(page);
            List<AssTransferInfoDTO> resultList = (List<AssTransferInfoDTO>) page.getResultList();
            ListPageVO<AssTransferInfoDTO> listPage = new ListPageVO<>(resultList, page.getTotalCount());
            return listPage;
        } catch (BaseException e) {
            BaseLogUtils.newLogger("查询过户信息列表数据业务异常！操作人：" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("查询过户信息列表数据系统异常！操作人：" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
    }

    @RequestMapping(value = "/queryFlowData.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object queryFlowData(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        try {
            // 流程实例ID
            String processInstanceId = request.getParameter("procId");
            if (StringUtils.isEmpty(processInstanceId)) {
                throw new BaseException("流程实例ID不能为空！");
            }
            String wordInTheTable = request.getParameter("table");

            SysFlowSHQueryCondition flowQc = new SysFlowSHQueryCondition();
            if (StringUtils.isNotEmpty(wordInTheTable)) {
                flowQc.setWordsInTheTable(wordInTheTable);
            } else {
                flowQc.setWordsInTheTable(InterfaceConstants.ASS_FLOW_S_H_ASS);
            }
            flowQc.setpInstId(processInstanceId);
            flowQc.setSysCd(CurrentThreadContext.getCurrentSysCd());

            List<SysFlowSHDTO> flowSHList = flowQueryApiService.searchFlowSHList(flowQc);
            if (CollectionUtils.isEmpty(flowSHList)) {
                throw new BaseException("未找到流程历史记录！");
            }
            result.setData(flowSHList.get(0));
        } catch (BaseException e) {
            BaseLogUtils.newLogger("查询流程历史数据异常").setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.newLogger("查询流程历史数据异常").setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
        }
        return result;
    }

    /**
     * 新增过户信息数据
     * @param request
     * @return
     */
    @RequestMapping(value = "/addAssTransferInfo.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addAssTransferInfo(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        try {
            AssTransferInfoDTO entity = this.getRequestParams(request);
            Long id = this.assDealCarService.addAssTransferInfo(entity);
            if (StringUtils.isEmpty(id)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_ADD_FAIL);
                return result;
            }
            AssDealCarVO vo = new AssDealCarVO();
            vo.setId(entity.getDealId());
            vo.setTnId(id);
            boolean success = this.assDealCarService.modify(vo);
            if (false == success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                return result;
            }
        } catch (BaseException e) {
            BaseLogUtils.newLogger("查询流程历史数据异常").setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.newLogger("查询流程历史数据异常").setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
        }
        return result;
    }

    private AssTransferInfoDTO getRequestParams(HttpServletRequest request) {
        AssTransferInfoDTO entity = new AssTransferInfoDTO();
        // 过户信息id
        String id = request.getParameter("id");
        if (StringUtils.isNotEmpty(id)) {
            entity.setId(Long.valueOf(id));
        }
        // 转优车id
        String dealId = request.getParameter("dealId");
        if (StringUtils.isNotEmpty(dealId)) {
            entity.setDealId(Long.valueOf(dealId));
        }
        // 过户项目
        String category = request.getParameter("category");
        if (StringUtils.isNotEmpty(category)) {
            entity.setCategoryCd(category);
        }
        // 完成时间
        String emtimateTime = request.getParameter("emtimateTime");
        if (StringUtils.isNotEmpty(emtimateTime)) {
            entity.setEstimateTime(DateUtils.formatStringToDate(emtimateTime, DateUtils.YYYY_MM_DD));
        }
        // 完成情况
        String completionStatus = request.getParameter("completionStatus");
        if (StringUtils.isNotEmpty(completionStatus)) {
            entity.setCompletionStatus(completionStatus);
        }
        // 过户金额
        String amount = request.getParameter("amount");
        if (StringUtils.isNotEmpty(amount)) {
            entity.setAmount(DecimalUtils.convertYuanToFen(Double.valueOf(amount)));
        }
        // 备注
        String remark = request.getParameter("remark");
        if (StringUtils.isNotEmpty(remark)) {
            entity.setRemark(remark);
        }
        entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        entity.setCrtTm(new Date());
        return entity;
    }

    /**
     * 到查看诉讼资料页面
     */
    @RequestMapping(value = "/toAssDealCarFilePage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAssDealCarFilePage(HttpServletRequest request) {
        String id = request.getParameter("id");
        String tableNm = request.getParameter("tableNm");
        ModelAndView view = new ModelAndView("ass/assDealCar/assDealCarFilePage");
        view.addObject("id", id);
        view.addObject("tableNm", tableNm);
        return view;
    }

    /**
     * 初始化诉讼记录资料grid
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/initAssDealCarFileCfgGrid.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initSueBscInfoFileCfgGrid(HttpServletRequest request) {
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id)) {
            throw new BaseException("主键id不能为空");
        }
        try {
            AssProFileQC condition = new AssProFileQC();
            condition.setOptimalId(Long.valueOf(id));
            condition.setOrgCd(AssFileConstant.ASS_PRO_ORG_CD);
            condition.setSysCd(AssFileConstant.ASS_PRO_SYS_CD);
            List<String> cfgCdList = new ArrayList<>();
            cfgCdList.add(AssFileConstant.ASS_PRO_FILE_CFG_CD_005);
            condition.setCfgCdList(cfgCdList);
            List<AssProFileVO> list = this.assDealCarService.searchAssProCfgDtlAndFileCfg(condition);
            BaseLogUtils.newLogger("查询转优车过户进度资料完成").setKeys("list:" + JSONObject.toJSONString(list)).info();
            if (CollectionUtils.isNotEmpty(list)) {
                return new ListPageVO<AssProFileVO>(list, list.size());
            } else {
                return new ListPageVO<AssProFileVO>();
            }
        } catch (BaseException e) {
            BaseLogUtils.newLogger("查询转优车过户进度资料失败").setKeys("id:" + id).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("查询转优车过户进度资料失败").setKeys("id:" + id).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
    }

}

